<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 增</el-button>

        <!--<el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permissionList.delBtn"
          @click="handleDelete"
        >删 除
        </el-button>-->
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.terminal_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.terminal_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{ row }" slot="isOn">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="row.isOn"
          @change="handleSwitch(row)"
        >
        </el-switch>
      </template>
      <!-- 总交易笔数 -->
      <template slot-scope="{row}" slot="rsSn">
        <div :class="row.rpmNo == 'R00001' ?'rsSnblue':' '" @click.stop="getqrCodeUrl(row)">{{row.rsSn}}</div>
      </template>

      <!-- 操作栏 -->
      <template slot-scope="scope" slot="menu">
        <!-- <el-button icon="el-icon-view" size="small" type="text" @click.stop="handleView(scope.row, scope.index)">查 看
        </el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row, scope.index)">编 辑
        </el-button> -->
        <!-- <el-button icon="el-icon-key" size="small" type="text" v-if="permissionList.delBtn"
                   @click.stop="rowDel(scope.row)">解 绑
        </el-button> -->
        <el-button size="small" type="text" v-if="permissionList.delBtn"
                   @click.stop="goto(scope.row)">终端管理
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 新建 -->
    <el-dialog
      :title="terminalDialog.text"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="terminalDialog.visible"
      v-if="terminalDialog.visible"
      :before-close="terminalDialogHandleClose"
      ref="terDialog"
    >
      <!-- <terminalDialog  ref="terminalDialog" :terminalDialog="terminalDialog" :terminalDialogForm="terminalDialogForm"/> -->
      <terminalDialog ref="terminalDialog" :terminalDialog="terminalDialog" :rptNoList="rptNoList" :terminalDForm="terminalDForm"/>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="() => { terminalDialog.visible = false; this.$refs['terminalDialog'].initEmpty();}">取 消</el-button>
        <el-button type="primary" v-preventClick @click="terminalDialogSubmit"
                   v-if="!terminalDialog.disabled">确 定</el-button>
      </span>
    </el-dialog>

    <el-image-viewer
      style="z-index: 2048"
      v-if="payVoucherDialog"
      :on-close="()=>{ payVoucherDialog = false }"
      :url-list="[rqUrlImage]"
    ></el-image-viewer>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form :model="towPwdForm" ref="towPwdForm" label-width="0" class="demo-ruleForm">
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            { required: true,message: '二级密码不能为空', trigger: ['change','blur']},
            { pattern: /^[0-9]{6}$/, message: '二级密码由6位数字组成', trigger: ['change','blur']}
          ]"
          >
          <el-input show-password v-model.number="towPwdForm.towPwd" autocomplete="off" placeholder="输入二级密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  addTerminal,
  editTerminal,
  remove,
  incomingTerminalOn,
  getRptNo,
  getModelList,
  getrpiNo,
  getstoreNo,
  getrpstNo,
  removeSM,
  removePOS,
  unBindZNJ
} from "@/api/rb-service/terminal/terminal";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";
import terminalDialog from "./terminalDialog";
import { userHasInfo } from "@/api/rb-service/forgetPassword/forgetPassword";
import md5 from 'js-md5';
import { remove as terRemove } from "@/api/rb-service/posinfo/terminal/taika";

export default {
  components: {
    terminalDialog
  },
  data() {
    return {
      payVoucherDialog: false,
      rqUrlImage: [],
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth:100,
        addBtn: false,//取消表格 新建/添加
        editBtn:false,
        viewBtn:false,
        delBtn:false,
        viewTitle:'修 改',
        menuWidth:110,
        column: [
          {
            label: "机构编号",
            prop: "serNo",
            type: "input",
            display:false,
            width: 140
          },
          {
            label: "机构名称",
            prop: "serCompany",
            type: "input",
            display:false,
            width: 200
          },
          {
            label: "直属代理编号",
            prop: "serviceNo",
            type: "input",
            width: 120,
            display:false,
            overHidden: true
          },
          {
            label: "直属代理名称",
            prop: "serviceName",
            type: "input",
            minWidth:200,
            display:false,
            overHidden: true
          },
          {
            label: "终端简称",
            prop: "rtName",
            type: "input",
            width: 150,
            overHidden: true,
            display: false,
            minWidth:200
          },
          {
            label: "终端编号",
            prop: "rsSn",
            type: "input",
            search: true,
            slot: true,
            minWidth:200,
            rules: [
              {
                required: true,
                message: "请输入终端编号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "商户编号",
            prop: "rpiNoCopy",
            type: "select",
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入商户",
                trigger: "blur",
              },
            ],
            width: 140,
            overHidden: true,
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            width: 200,
            display: false
          },
          {
            label: "商户",
            prop: "rpiNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 4,
            hide: true,
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入商户",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpiName',
              value: 'rpiNo',
              desc:'rpiNo'
            },
            // remote: true,
            dicData: [],
            // dicUrl: `/api/rb-service/service/incomingbasic/incoming_basic/list?current=-1&size=-1&rpiKind=0&rpiName={{key}}`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            change: (value) => {
              if (value) {
                this.search.storeNo = '';
                this.storeNoList = [];
                this.search.rpstNo = '';
                this.rpstNoList = [];
                if (value.value) {
                  this.rpiNoListChange(value.value);//门店
                }
              }
            }
          },
          {
            label: "门店",
            prop: "storeName",
            type: "input",
            display: false,
            minWidth:160,
          },
          {
            label: "门店",
            prop: "storeNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 5,
            hide: true,
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入门店",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc:'rpsNo'
            },
            // dicUrl: `/api/rb-service/service/posStore/pos_store/listV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: [],
            change: (value) => {
              if (value) {
                this.search.rpstNo = '';
                this.rpstNoList = [];
                if (value.value) {
                  this.apiRpstList(value.value);//收银员
                }
              }
            }
          },
          {
            label: "收银员",
            prop: "rpstName",
            type: "input",
            width: 150,
            display: false
          },
          {
            label: "收银员",
            prop: "rpstNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 6,
            searchLabelWidth: 94,
            hide: true,
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入收银员",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpstName',
              value: 'rpstNo',
              desc:'rpstNo'
            },
            // dicUrl: `/api/rb-service/service/posStaff/pos_staff/listV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: []
          },
           {
            label: "类型",
            prop: "rptName",
            type: "input",
            overHidden: true,
            display: false
          },
          {
            label: "类型",
            prop: "rptNo",
            type: "select",
            overHidden: true,
            search: true,
            searchOrder: 1,
            hide: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入类型",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rptName',
              value: 'rptNo',
              desc:'rptNo'
            },
            filterable: true,
            dicData: [],
            change: (value) => {
              if (value) {
                // 获取型号
                // this.search.rpsNo = '';
                // this.rpsNoList = [];
                this.search.rpmNo = '';
                this.rpmNoList = [];
                if (value.value) {
                  this.apiModelListList(value.value);//型号
                }
              }
            }
          },
          {
            label: "型号",
            prop: "rpmName",
            type: "input",
            display: false,
            minWidth:140,
            overHidden:true
          },
          {
            label: "型号",
            prop: "rpmNo",
            type: "select",
            sortable: true,
            search: true,
            searchOrder: 3,
            hide: true,
            display: false,
            filterable: true,
            rules: [
              {
                required: true,
                message: "请输入型号",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpmName',
              value: 'rpmNo',
              desc:'rpmNo'
            },
            // dicUrl: `/api/rb-service/service/terminal/terminal/modelListV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: []
          },
          {
            label: "终端状态",
            prop: "isOn",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=is_on",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            display: false,
            rules: [
              {
                required: true,
                message: "请选择终端状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "绑定时间",
            prop: "createTime",
            type: "input",
            minWidth: 140,
            rules: [
              {
                required: true,
                message: "请输入终端编号",
                trigger: "blur",
              },
            ],
            display:false,
            overHidden: true
          }
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      terminalDialog: {
        disabled: false,
        visible: false,
        type: 'add',
        text: '新建'
      },//表格右侧操作add,edit,view
      terminalDForm: {},//终端表单
      rptNoList: [],//类型
      rpsNoList: [],//供应商名称
      rpmNoList: [],//型号
      storeNoList: [],//门店
      rpstNoList: [],//收银员
      hasPayPwd:false,
      twoPwdShow:false,
      towPwdForm:{
        towPwd:'',
        ids:'',
        rprNo:"",
        rsSn:"",
        rptNo:""
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.terminal_add, false),
        viewBtn: this.vaildData(this.permission.terminal_view, false),
        delBtn: this.vaildData(this.permission.terminal_delete, false),
        editBtn: this.vaildData(this.permission.terminal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    // 'search.rptNo'(newVal, oldVal) {
    //     if (newVal !== oldVal) {
    //       this.search.rpsNo = '';
    //       const rpsNo = this.findObject(this.option.column, "rpsNo");
    //       rpsNo.dicData = [];
    //       this.search.rpmNo = '';
    //       const rpmNo = this.findObject(this.option.column, "rpmNo");
    //       rpmNo.dicData = [];
    //     }
    //   },
  },
  methods: {
    // 二级密码 关闭回调
    handleCloseTwoPwd(done){
      this.towPwdForm.towPwd="";
      done()
    },
    // 二级密码 确定
    twoPwdSubmit(){
      let that = this;
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          if(that.towPwdForm.rptNo == 18){
            remove(that.towPwdForm.ids,md5(that.towPwdForm.towPwd+'')).then((res) => {
              that.onLoad(this.page);
              that.$message({
                type: "success",
                message: res.data.msg
              });
              that.$refs.crud.toggleSelection();
              that.twoPwdShow = false;
              that.towPwdForm.towPwd="";
            });
          } else if(that.towPwdForm.rptNo == 20){
             let param ={
                rsSn:that.towPwdForm.rprNo,
                rpiNo:that.towPwdForm.rpiNo,
                payPwd:md5(that.towPwdForm.towPwd+'')
              }
            removePOS(param).then((res) => {
              that.onLoad(this.page);
              that.$message({
                type: "success",
                message: res.data.msg
              });
              that.$refs.crud.toggleSelection();
              that.twoPwdShow = false;
              that.towPwdForm.towPwd="";
            });
          } else if(that.towPwdForm.rptNo == 23){
             let param ={
                rsSn:that.towPwdForm.rprNo,
                rpiNo:that.towPwdForm.rpiNo,
                payPwd:md5(that.towPwdForm.towPwd+'')
              }
            removeSM(param).then((res) => {
              that.onLoad(this.page);
              that.$message({
                type: "success",
                message: res.data.msg
              });
              that.$refs.crud.toggleSelection();
              that.twoPwdShow = false;
              that.towPwdForm.towPwd="";
            });
          } else if(that.towPwdForm.rptNo == 24){
             let param ={
                rsSn:that.towPwdForm.rprNo,
                rpiNo:that.towPwdForm.rpiNo,
                payPwd:md5(that.towPwdForm.towPwd+'')
              }
            unBindZNJ(param).then((res) => {
              that.onLoad(this.page);
              that.$message({
                type: "success",
                message: res.data.msg
              });
              that.$refs.crud.toggleSelection();
              that.twoPwdShow = false;
              that.towPwdForm.towPwd="";
            });
          } else{ 
            let param={
              payPwd:md5(that.towPwdForm.towPwd+''),
              rprNo: that.towPwdForm.rprNo,
              rsSn: that.towPwdForm.rsSn
            }
            
            terRemove(param).then((res) => {
              that.onLoad(this.page);
              that.$message({
                type: "success",
                message: res.data.msg
              });
              that.$refs.crud.toggleSelection();
              that.twoPwdShow = false;
              that.towPwdForm.towPwd="";
            });
          }
        } else {
          return false;
         }
      });
    },
    // 是否 有二级密码
    getUserHasInfo(){
      userHasInfo().then(res =>{
        this.hasPayPwd = res.data.data.hasPayPwd;
      }, error => {
        window.console.log(error);
      })
    },
    // 跳转用户信息页面
    toUserInfo(){
      this.$confirm('请您先设置二级密码，再操作！', '提示', {
        confirmButtonText: '确定',
        showCancelButton:false,
        type: 'warning'
      }).then(() => {
        this.$router.push({ path: '/info/index', query: { index: 2 }})
      })
    },
    // 跳转 商户详情终端管理
    goto(row){
      let terminalIndex = 0;

      // if(row.rpmNo == 'R00001'){
      //   terminalIndex = 0;
      // }else if(row.rpmNo == 'A00001'){
      //   terminalIndex = 2;
      // }
      if(row.rptNo == '15'){//台卡
        terminalIndex = 0;
      }else if(row.rptNo == '18'){//第三方
        terminalIndex = 2;
      }else if(row.rptNo == '23'){//扫码设备
        terminalIndex = 3;
      }else if(row.rptNo == '20'){//传统POS
        terminalIndex = 4;
      }

      this.$router.push({
        name: "终端管理",
        query: {
          rpiNo: row.rpiNo,
          terminalIndex
        },
      });
    },
    //查看二维码
    getqrCodeUrl(item) {
      if(item.rpmNo == 'R00001'){
        this.rqUrlImage[0] = item.qrcodeUrl;
        this.payVoucherDialog = true;
      }
    },
    // 新建
    handleSave() {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'add';
      this.terminalDialog.text = "新建终端";
      this.terminalDialog.disabled = false;
    },
    // 编辑
    handleEdit(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'edit';
      this.terminalDialog.text = "修改终端";
      this.terminalDialog.disabled = false;
      this.terminalDForm = JSON.parse(JSON.stringify(row));

    },
    handleView(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'view';
      this.terminalDialog.text = "查看";
      this.terminalDialog.disabled = true;
      this.terminalDForm = JSON.parse(JSON.stringify(row));

    },
    /**
     * @func 终端状态开关
     * @desc 终端状态开关 0否 1是
     * @param {Object} row - 终端信息
     * */
    handleSwitch(row) {
      incomingTerminalOn(row.id, row.isOn).then(
        () => {},
        (error) => {
          row.isOn = row.isOn == 1 ? 0 : 1;
          window.console.log(error);
        }
      );
    },
    // 保存
    rowSave(row, done, loading) {
      addTerminal(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      editTerminal(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
        this.towPwdForm.ids = row.id;
        this.towPwdForm.rptNo = row.rptNo;//设备类型编号
        this.towPwdForm.rpiNo = row.rpiNo,//商户编号
        this.towPwdForm.rprNo = row.rsSn
        this.twoPwdShow = true;
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if(!this.hasPayPwd){
        this.toUserInfo();
      } else {
        this.towPwdForm.ids = this.ids;
        this.twoPwdShow = true;
      }
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, {eqType: 1})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rtName=${this.search.rtName}`;
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      // exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&storeNo=${this.search.storeNo}`;
      exQuery += `&rpstNo=${this.search.rpstNo}`;
      exQuery += `&rtPara=${this.search.rtPara}`;
      exQuery += `&isOn=${this.search.isOn}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/terminal/terminal/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/terminal/terminal/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    // 终端---新建弹框 关闭前回调
    terminalDialogHandleClose(done) {
      this.$refs['terminalDialog'].initEmpty();
      done();
    },
    clickCopy(ht) {
      const save = function(e) {
        e.clipboardData.setData('text/plain', ht)
        e.preventDefault() // 阻止默认行为
      }
      const once = {
        once: true
      }
      document.addEventListener('copy', save,once) // 添加一个copy事件
      document.execCommand('copy') // 执行copy方法
      this.$message({ message: '复制成功', type: 'success' })
    },
    // 终端---新建弹框提交
    terminalDialogSubmit() {
      /**
       * add  新建
       * edit 修改
       * view 查看详情
       */
      let that = this;
      if (this.terminalDialog.type !== 'view') {
        this.$refs['terminalDialog'].$refs['terminalDialogForm'].validate((valid) => {
          if (valid) {
            if(this.$refs['terminalDialog'].terminalDialogForm.rpmNo == 'A00001'){
              this.$refs['terminalDialog'].terminalDialogForm.rsSn = ''
            }

            let param = {
              ...this.$refs['terminalDialog'].terminalDialogForm
            }
            if (this.terminalDialog.type == 'add') {
              if(param.rpmNo == 'A00001'){
                addTerminal(param).then((res) => {
                  const h = this.$createElement;
                  this.$msgbox({
                    title: '',
                    message: h('div', null, [
                      h('h4', { style:'margin:0 0 10px 0;color:#f00;' }, res.data.msg),
                      h('div', null, `商户号：${param.rpiNo}`),
                      h('div', null, `终端号：${res.data.data.appkey}`),
                      h('div', null, `密钥(token)：${res.data.data.secret}`)
                    ]),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '复制',
                    showClose:false,
                    beforeClose: (action,instance,done) => {
                      if (action === 'confirm') {
                        // instance.confirmButtonLoading = true;
                        // instance.confirmButtonText = '执行中...';
                        done();
                      } else {
                        let text = `商户号：${param.rpiNo},终端号：${res.data.data.appkey},密钥(token)：${res.data.data.secret}`;
                        that.clickCopy(text);
                      }
                    }
                  }).then(() => {
                    that.onLoad(this.page);
                    that.$refs['terminalDialog'].initEmpty();
                    that.$message({
                      type: "success",
                      message: "操作成功!",
                    });
                    that.terminalDialog.visible = false;
                  });
                },(error) => {
                    window.console.log(error);
                  }
                );
              }else{
                addTerminal(param).then(() => {
                  that.onLoad(this.page);
                  that.$refs['terminalDialog'].initEmpty();
                  that.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  that.terminalDialog.visible = false;
                },(error) => {
                    window.console.log(error);
                  }
                );
              }
            } else if (this.terminalDialog.type == 'edit') {
              editTerminal(param).then(() => {
                this.onLoad(this.page);
                this.$refs['terminalDialog'].initEmpty();

                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.terminalDialog.visible = false;
              },(error) => {
                  window.console.log(error);
                }
              );
            }
            
          }
        });

      }
    },
    // 获取 类型名称
    requestRptNo() {
      getRptNo(-1, -1,{eqType:1}).then((res) => {
        this.rptNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rptNo");
        column.dicData = this.rptNoList;
        this.$forceUpdate();
      })
    },
    // 获取 商户
    requestrpiNo() {
      getrpiNo(-1, -1).then((res) => {
        this.rpiNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpiNo");
        column.dicData = this.rpiNoList;
        this.$forceUpdate();
      })
    },
    // 获取型号
    apiModelListList(rptNo = "") {
      let param ={};
      if(rptNo){
        param.rptNo = rptNo;
      }
      getModelList(-1, -1, param).then((res) => {
        this.rpmNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpmNo");
        column.dicData = this.rpmNoList;
        this.$forceUpdate();
      })
    },
    // 获取 门店名称
    rpiNoListChange(rpiNo = "") {
      let param ={};
      if(rpiNo){
        param.rpiNo = rpiNo;
      }
      getstoreNo(-1, -1, param).then((res) => {
        this.storeNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "storeNo");
        column.dicData = this.storeNoList;
        this.$forceUpdate();
      })
    },
    // 获取 收银员名称
    apiRpstList(rpsNo = "") {
      let param ={};
      if(rpsNo){
        param.rpsNo = rpsNo;
      }
      getrpstNo(-1, -1, param).then((res) => {
        this.rpstNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpstNo");
        column.dicData = this.rpstNoList;
        this.$forceUpdate();
      })
    },
   
    // 获取供应商
    //     this.search.rpsNo = '';
    //     this.rpsNoList = [];
    //     this.search.rpmNo = '';
    //     this.rpmNoList = [];
    //     if (value.value) {
    //       getRpsNo(-1, -1, {rptNo: value.value}).then((res) => {
    //         this.rpsNoList = res.data.data.records;
    //         const column = this.findObject(this.option.column, "rpsNo");
    //         column.dicData = this.rpsNoList;
    //       })
    //     }
    
    initRequest() {
      this.requestRptNo();//获取 类型

      this.apiModelListList();//型号

      this.requestrpiNo();//获取 商户

      // this.rpiNoListChange();//门店
      
      this.apiRpstList();//收银员名称

      this.getUserHasInfo()
    }
  },
  created() {
    this.initRequest()
  },
};
</script>

<style lang="scss" scoped>
.rsSnblue{
  color: #409eff;
  cursor: pointer;
}
</style>
